package com.ppblock.shirox.controller;

import com.ppblock.shirox.core.AuthenticationInfo;
import com.ppblock.shirox.core.SubjectManager;
import com.ppblock.shirox.core.impl.UsernamePasswordToken;
import com.ppblock.shirox.surpport.RequiresPermissions;
import com.ppblock.shirox.utils.AuthorizationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yangjian
 * @since 17-12-6.
 */
@Controller
@RequestMapping("/")
public class DemoController {

	@RequestMapping("/")
	@RequiresPermissions("user:index")
	public String index(HttpServletRequest request) {
		return "index";
	}

	@RequestMapping("/login")
	public String login(HttpServletRequest request) {
		return "login";
	}

	@PostMapping("/doLogin")
	@ResponseBody
	public String doLogin(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		SubjectManager manager = AuthorizationUtils.getAuthorizationManager();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		manager.login(token);
		AuthenticationInfo info = manager.getAuthenticationInfo().getPrimaryAuthenticationInfo();
		if (manager.isAuthorized()) {
			return "Login Successfully, "+ info.getUserInfo();
		} else {
			return "Login Faild.";
		}
	}

	@RequestMapping("/logout")
	@ResponseBody
	public String logout(HttpServletRequest request) {
		SubjectManager manger = AuthorizationUtils.getAuthorizationManager();
		manger.logout();
		return "Logout safely.";
	}

	@RequestMapping("/add")
	@RequiresPermissions("user:add")
	@ResponseBody
	public String add(HttpServletRequest request) {
		return "Add a item successfully.";
	}

	@RequestMapping("/check")
		@RequiresPermissions("user:check")
	@ResponseBody
	public String check(HttpServletRequest request) {
		return "Check The User XiaoMing";
	}

	@RequestMapping("/403")
	public String unAuthorized(HttpServletRequest request) {
		return "un_authorized";
	}

}
